<template>
  <div style="display: flex; margin-top: 20px">
    <el-form-item style="margin-left: 10px" label="文件名"
      ><el-input v-model="name" placeholder="请输入要查找的文件名"
    /></el-form-item>
    <el-button
      style="margin-left: 20px"
      @click="search"
      type="primary"
      :icon="Upload"
      >搜 索</el-button
    >
    <el-button
      style="margin-left: 20px"
      @click="showUpload = true"
      type="primary"
      :icon="Upload"
      >上 传</el-button
    >
    <el-button
      style="margin-left: 20px"
      @click="newFolder"
      type="primary"
      :icon="FolderAdd"
      >新建文件夹</el-button
    >
  </div>
  <myNavigator @update="handleUpdate" />
  <el-table :data="tableData" :border="true" style="width: 1200px">
    <el-table-column width="50">
      <template #default="{ row }">
        <el-image
          v-if="row.icon"
          :src="'data:image/png;base64,' + row.icon"
          fit="contain"
        />
      </template>
    </el-table-column>
    <el-table-column label="文件名" class-name="fileNameClass">
      <template #default="{ row }"
        ><div @click="handleFileNameClick(row)">{{ row.name }}</div></template
      >
    </el-table-column>
    <el-table-column
      prop="lastTime"
      label="上次修改日期"
      :formatter="formatDate"
    />
    <el-table-column
      v-if="showSearchResult"
      prop="path"
      label="路径"
      :formatter="formatPath"
    />
    <el-table-column label="大小" prop="length" :width="lengthWidth" />
    <el-table-column label="操作"
      ><template #default="{ row }">
        <!-- 在这里插入按钮并绑定事件 -->
        <el-button
          @click="download(row)"
          size="small"
          type="primary"
          :icon="Download"
          v-if="row.length"
          >下载</el-button
        >
        <el-button
          @click="deleteHandler(row)"
          size="small"
          type="danger"
          :icon="DocumentRemove"
          >删除</el-button
        >
        <el-button
          @click="renameHandler(row)"
          size="small"
          type="info"
          :icon="Edit"
          >重命名</el-button
        >
      </template></el-table-column
    >
  </el-table>
  <el-dialog v-model="showRename">
    <el-form-item label="重命名"
      ><el-input
        v-model="newName"
        style="width: 240px"
        placeholder="请输入文件新名称"
    /></el-form-item>
    <el-button :icon="FolderChecked" type="primary" @click="submit"
      >确 定</el-button
    >
  </el-dialog>
  <el-dialog v-model="showUpload"
    ><MyUpload @messageToParent="receiveMessage"
  /></el-dialog>
  <el-dialog v-model="showNewFolder">
    <el-form-item label="文件夹名">
      <el-input
        v-model="newName"
        style="width: 240px"
        placeholder="请输入文件夹新名称"
      />
    </el-form-item>
    <el-button :icon="FolderChecked" type="primary" @click="submit"
      >确 定</el-button
    >
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue"; // 引入 Vue 3 的生命周期钩子
import fileApi from "../api/file";
import folderApi from "@/api/folder";
import { ElMessage, ElMessageBox } from "element-plus";
import myNavigator from "./myNavigator.vue";
import {
  Download,
  DocumentRemove,
  Edit,
  FolderChecked,
} from "@element-plus/icons-vue";
import { Upload, FolderAdd } from "@element-plus/icons-vue";
import MyUpload from "../components/myUpload.vue";
import dayjs from "dayjs";
import store from "@/store";

const name = ref(""); //查询参数
const showUpload = ref(false); // 控制是否渲染组件
const tableData = ref([]); // 使用 ref 定义响应式数据
const showRename = ref(false); //控制是否显示重命名对话框
const newName = ref(null); //文件或文件夹新名称
const pageSize = ref(10); //每页显示的数量
const total = ref(0); //文件总数
const currentPage = ref(1); //当前在第几页
const showNewFolder = ref(false); //控制是否显示新建文件夹对话框
const showSearchResult = ref(false); //显示搜索结果
let fileFullPath; //文件的全路径
const lengthWidth = ref(""); //表格中文件大小列的宽度

// 在组件挂载后获取数据
onMounted(async () => {
  await getFileList();
});

watch(showRename, (newValue) => {
  if (!newValue) {
    newName.value = null;
  }
});

const receiveMessage = async () => {
  await getFileList();
};

const getFileList = async () => {
  // const response = await fileApi.getList(name.value); // 替换为实际的 API 地址
  // tableData.value = response.data; // 将数据赋值给 tableData
  if (showSearchResult.value) {
    const res = await fileApi.getList(name.value);
    tableData.value = res.data;
  } else {
    const res = await folderApi.enterFolder();
    tableData.value = res.data;
  }
};

const download = (data) => {
  fileApi.download(data.path, data.name);
};

const deleteFile = async (data) => {
  const result = await fileApi.delete(data);
  ElMessage({
    type: "success",
    message: `${result.data}`,
  });
  getFileList();
};

const deleteHandler = async (data) => {
  ElMessageBox.confirm(
    "删除操作将永久删除文件，不可恢复！确定继续吗？",
    "Warning",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      deleteFile(data.path);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除！",
      });
    });
};

const renameHandler = async (data) => {
  newName.value = data.name;
  showRename.value = true;
  fileFullPath = data.path;
};

const submit = async () => {
  //文件重命名
  if (showRename.value) {
    if (newName.value) {
      ElMessageBox.confirm(`确定将文件重命名为${newName.value}吗`, "Warning", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          setName(newName.value);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消操作!",
          });
        });
    } else {
      ElMessage.error("文件命名不得为空！");
    }
  }
  //新建文件夹
  if (showNewFolder.value) {
    if (newName.value) {
      const res = await folderApi.newFolder(newName.value);
      ElMessage({
        message: `${res.data}`,
        type: "success",
      });
      showNewFolder.value = false;
      newName.value = null;
      getFileList();
    } else {
      ElMessage.error("文件夹名不得为空！");
    }
  }
};

const setName = async (newName) => {
  const res = await fileApi.rename(fileFullPath, newName);
  ElMessage({
    type: "success",
    message: `${res.data}`,
  });
  // const response = await fileApi.getList(name.value);
  // tableData.value = response.data;
  getFileList();
  showRename.value = false;
};

const search = async () => {
  store.commit("resetStack");
  const response = await fileApi.getList(name.value); // 替换为实际的 API 地址
  tableData.value = response.data; // 将数据赋值给 tableData
  showSearchResult.value = true;
  lengthWidth.value = "100";
};

/**
 * 日期格式化
 */
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return ""; // 如果没有值，返回空字符串
  return dayjs(cellValue).format("YYYY年MM月DD日 HH:mm:ss"); // 使用 dayjs 格式化日期
};

/**
 * 路径格式化
 */
const formatPath = (row, column, cellValue) => {
  const rootPath = " D:\\uploads\\";
  // 查找 "D:\\uploads\\" 的位置
  const startIndex = cellValue.indexOf(rootPath);
  // 截取 "D:\\uploads\\" 之后的部分
  // 查找最后一次出现的 '\\' 的位置
  const lastIndex = cellValue.lastIndexOf("\\");
  const result = cellValue.substring(startIndex, lastIndex);
  return result;
};

const newFolder = async () => {
  showNewFolder.value = true;
};

const handleFileNameClick = async (data) => {
  if (data.length) {
    //有长度代表是文件
    //todo 后面要打开预览该文件
    const index = data.name.lastIndexOf(".");
    const type = data.name.substring(index + 1, data.name.length);
    previewFile(type);
  } else {
    //没有长度代表是文件夹
    store.commit("newPage", data.name);
    const res = await folderApi.enterFolder();
    tableData.value = res.data;
  }
};

/**
 * 预览文件
 * @param data 文件的类型，比如txt，jpg，MP4，xlsx等等
 */
const previewFile = async (data) => {
  switch (data) {
    case "xlsx":
      console.log("excel");
      break;
    case "docx":
      console.log("word");
      break;
    default:
      console.log("不支持的文件类型");
  }
};

const handleUpdate = async () => {
  const params = store.getters.getBackTop;
  const res = await folderApi.skipRouter(params);
  tableData.value = res.data;
};
</script>

<style>
/* 样式自定义 */

.fileNameClass:hover {
  cursor: pointer;
  color: #009fcc;
}
</style>
